package com.clear.wechat.utils;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class MessageUtil {

    /**
     * 解析微信发过来的请求（xml）
     *
     * @param msg 消息
     * @return
     */
    public static Map<String, String> parseXml(final String msg) {
        Map<String, String> map = new HashMap<>();

        // 从request中获取输入流
        Document document;
        try (ByteArrayInputStream inputStream = new ByteArrayInputStream(msg.getBytes(StandardCharsets.UTF_8.name()))) {
            // 读取输入流
            SAXReader saxReader = new SAXReader();
            document = saxReader.read(inputStream);
            // 得到xml根元素
            Element root = document.getRootElement();
            // 得到根元素下所有子节点
            root.elements().forEach(element -> {
                String name = element.getName();
                String text = element.getText();
                map.put(name, text);
            });
        } catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }
}
